package com.hazardSoft.eStore.bussines;

import java.util.LinkedList;
import java.util.List;

import javax.persistence.EntityManager;

import com.hazardSoft.eStore.common.exception.SystemException;
import com.hazardSoft.eStore.entities.Bill;
import com.hazardSoft.eStore.entities.Sale;
import com.hazardSoft.eStore.utils.Dates;
import com.hazardSoft.eStore.utils.PathConstants;

public class BillsBO {
	
	private static final String CLASS_NAME = PathConstants.BUSSINES_PATH+BillsBO.class.getSimpleName();
	
	public Bill insertBil(Bill bill ,EntityManager entityManager) throws SystemException{
		if (bill == null) {
			throw new SystemException(new Exception("null bill"), CLASS_NAME, "insertBill");
		}
		if (bill.getClient() == null) {
			throw new SystemException(new Exception("null bill.client"), CLASS_NAME, "insertBill");
		}
		if (bill.getSaleCollection() == null) {
			throw new SystemException(new Exception("null bill.salleCollection"), CLASS_NAME, "insertBill");
		}
		
		bill.setDate(Dates.calculateDate());
		entityManager.persist(bill);
		
		List<Sale> sales = new LinkedList<Sale>();
		
		SalesBO salesBO = new SalesBO();
		
		Double total = 0.0;
		
		for (Sale sale : bill.getSaleCollection()) {
			sale.setBill(bill);
			sale = salesBO.insertSale(sale, entityManager);
			if (!(sale == null)) {
				total += sale.getCost();
				sale = salesBO.searchSale(sale, entityManager);
				sales.add(sale);
				entityManager.clear();
			}
			System.out.println(sale.getId()+" "+sale.getProduct().getName()+" "+sale.getQuantity()+" "+sale.getCost()+" "+total);
		}
		bill.setTotal(total);
		entityManager.merge(bill);
		return bill;
	}
}
